package com.baijiayun.liveuibase.widgets.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.*;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.base.QueryPlus;
import com.baijiayun.liveuibase.utils.DisplayUtils;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder;

/**
 * 带标题栏的dialog
 * @author yongjiaming
 */
public abstract class BaseTitleDialog extends Dialog implements LifecycleObserver {

    protected Context context;
    protected QueryPlus $;
    private String title;
    private Lifecycle lifecycle;

    public BaseTitleDialog(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = LayoutInflater.from(context).inflate(R.layout.uibase_base_title_dialog, null);
        view.setBackground(ThemeDataUtil.getCommonWindowBg(context));
        $ = QueryPlus.with(view);
        $.id(R.id.base_dialog_title_text).text(title);
        $.id(R.id.base_dialog_title_close_iv).view().setOnClickListener(v -> {
            dismiss();
        });
        LayoutInflater.from(context).inflate(getContentLayout(), $.id(R.id.base_dialog_title_content_container).view());
        setContentView(view);
        if(lifecycle != null) {
            lifecycle.addObserver(this);
        }
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    protected abstract int getContentLayout();

    protected void destroy(){

    }

    public BaseTitleDialog setTitle(String title) {
        this.title = title;
        return this;
    }

    public BaseTitleDialog setLifecycle(Lifecycle lifecycle) {
        this.lifecycle = lifecycle;
        return this;
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if(lifecycle != null) {
           lifecycle.removeObserver(this);
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        if (lifecycle != null) {
            lifecycle.removeObserver(this);
        }
        destroy();
        dismiss();
    }
}
